import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/mysql';
import { getCurrentUser } from '@/lib/auth';

// 更新用户资料
export async function PUT(request: NextRequest) {
  try {
    // 验证用户身份
    const user = getCurrentUser();
    if (!user) {
      return NextResponse.json(
        { success: false, error: '请先登录' },
        { status: 401 }
      );
    }

    // 解析请求体
    const body = await request.json();
    const { username, school, grade } = body;

    // 更新用户名（如果提供）
    if (username && username !== user.username) {
      await query(
        `UPDATE users SET display_name = ? WHERE id = ?`,
        [username, user.userId]
      );
    }

    // 更新用户配置
    await query(
      `UPDATE user_profiles SET school = ?, grade = ? WHERE user_id = ?`,
      [school || null, grade || 1, user.userId]
    );

    return NextResponse.json({
      success: true,
      message: '个人资料已更新'
    });

  } catch (error) {
    console.error('更新用户资料错误:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : '更新失败' 
      },
      { status: 500 }
    );
  }
}

